﻿using CloudMusic.Helper;
using CloudMusic.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace CloudMusic.UC
{
    /// <summary>
    /// CloudMusicBanner.xaml 的交互逻辑
    /// </summary>
    public partial class UCMusicBanner : UserControl
    {
        public static ObservableCollection<BannersItem> bn = new ObservableCollection<BannersItem>();
        //代码所用涉及时间单位均是：秒
        #region 一些变量
        //左、中、右三张banner的位置
        double leftlocation = 0, centerlocation = 0, rightlocation = 0;
        //每张banner的动画执行时间
        double AnimationTime = 0.4;
        //非中间banner的遮盖层透明度
        double bopacity = 0.65;
        //没有交互时动画自动执行间隔时间
        double timeranimation_time = 5;
        //动画播放状态（当前动画是否在执行）
        bool isplay = false;
        //三个banner border变量，用于暂时保存
        Border b_left, b_center, b_right;
        //通用缓动函数，提升动画流畅感
        EasingFunctionBase easeFunction;
        //banner集合，用于定位和记录border的位置（左，中，右）
        Dictionary<Location, Border> Banners = new Dictionary<Location, Border>();
        DispatcherTimer timeranimation;
        private int pageIndex = 0;
        Button bt = default;
        #endregion

        public UCMusicBanner()
        {
            InitializeComponent();
            GetBanner();
            Banners.Add(Location.Left, left);
            Banners.Add(Location.Center, center);
            Banners.Add(Location.Right, right);
            this.SizeChanged += new SizeChangedEventHandler(MainWindow_Resize);
            leftImg.Source = new BitmapImage(new Uri(bn[bn.Count - 1].imageUrl));
            centerImg.Source = new BitmapImage(new Uri(bn[0].imageUrl));
            rightImg.Source = new BitmapImage(new Uri(bn[1].imageUrl));
            leftTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[bn.Count - 1].titleColor));
            leftTypeTitle.Text = bn[bn.Count - 1].typeTitle;
            centerTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[0].titleColor));
            centerTypeTitle.Text = bn[0].typeTitle;
            rightTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[1].titleColor));
            rightTypeTitle.Text = bn[1].typeTitle;
            //控件加载完成后
            Loaded += (e, c) =>
            {
                //将三张banner(border)添加到banner集合
                //首次启动设置三张banner的位置、大小信息
                SetLocation(Location.Left, left);
                SetLocation(Location.Center, center);
                SetLocation(Location.Right, right);
                //启动定时器，用于自动播放滚动动画
                TimerAnimationStart();

            };
            //初始化缓动函数
            //quadraticease的easeout mode是从快到慢
            easeFunction = new QuadraticEase()
            {
                EasingMode = EasingMode.EaseOut
            };
            //初始化定时器
            timeranimation = new DispatcherTimer();
            //设置定时器的间隔时间
            timeranimation.Interval = TimeSpan.FromSeconds(timeranimation_time);
        }

        #region banner部分
        public void GetBanner()
        {
            //var strJosn = CommonHelper.Get("http://localhost:3000/banner");
            //JObject obj = (JObject)JsonConvert.DeserializeObject(strJosn);
            //string data = obj["banners"].ToString();
            //JObject Banners = (JObject)JsonConvert.DeserializeObject(data);
            //string banner = Banners["banners"].ToString();
            //List<BannersItem> objs = JsonConvert.DeserializeObject<List<BannersItem>>(data);
            var list = CommonHelper.GetEquipList<MusicBannerModel>(1, "http://localhost:3000/banner");
            if (list == null) return;
            for (int i = 0; i < list.banners.Count; i++)
            {
                BannersItem item = new BannersItem();
                item.titleColor = list.banners[i].titleColor;
                item.typeTitle = list.banners[i].typeTitle;
                item.imageUrl = list.banners[i].imageUrl;
                item.monitorClick = list.banners[i].monitorClick;
                item.monitorImpress = list.banners[i].monitorImpress;
                item.monitorType = list.banners[i].monitorType;
                item.targetId = list.banners[i].targetId;
                item.targetType = list.banners[i].targetType;
                if (list.banners[i].targetType == 1 && list.banners[i].encodeId != "0")
                {
                    item.url = "/song?id=" + list.banners[i].encodeId;
                }
                else
                {
                    item.url = list.banners[i].url;
                }
                bn.Add(item);
                bt = new Button { Style = TryFindResource("RollBtn") as Style };
                bt.Tag = i;
                bt.Name = "bt" + i.ToString();
                bt.MouseEnter += new MouseEventHandler(IndexBtnEnter);
                bt.MouseLeave += new MouseEventHandler(IndexBtnLeave);
                indexBtn.Children.Add(bt); 
            }
            indexBtn.Children[0].SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C62F2F")));
        }

        #region 交互事件
        private void MainWindow_Resize(object sender, System.EventArgs e)
        {
            SetLocation(Location.Left, left);
            SetLocation(Location.Center, center);
            SetLocation(Location.Right, right);
        }

        private void UserControl_MouseEnter(object sender, MouseEventArgs e)
        {
            //鼠标移入控件时显示两个“左/右”图标按钮
            toleftbtn.Opacity = 1;
            torightbtn.Opacity = 1;
        }

        private void UserControl_MouseLeave(object sender, MouseEventArgs e)
        {
            //鼠标移出控件时隐藏两个“左/右”图标按钮
            toleftbtn.Opacity = 0;
            torightbtn.Opacity = 0;
        }

        private void toleftbtn_Click(object sender, RoutedEventArgs e)
        {
            //向左图标按钮点击
            if (pageIndex > 0)
            {
                pageIndex--;
            }
            else
            {
                pageIndex = bn.Count - 1;
            }
            SetBtnColor(pageIndex, "left");
            LeftAnimation();
        }

        private void torightbtn_Click(object sender, RoutedEventArgs e)
        {

            //向右图标按钮点击
            if (pageIndex < bn.Count - 1)
            {
                pageIndex++;
            }
            else
            {
                pageIndex = 0;
            }
            RightAnimation();
            SetBtnColor(pageIndex, "right");
        }
        /// <summary>
        /// 鼠标进入页码按钮时候停止动画
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IndexBtnEnter(object sender, MouseEventArgs e)
        {
            Button button = sender as Button;
            if (button.IsMouseOver == true)
            {
                for (int i = 0; i < indexBtn.Children.Count; i++)
                {
                    indexBtn.Children[i].SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C8C8C8")));
                }
                button.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C62F2F"));
                GetLoctionBannerUrl((int)button.Tag);
            }
        }
        /// <summary>
        /// 离开时唤醒动画
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IndexBtnLeave(object sender, MouseEventArgs e)
        {
            //此时动画结束
            isplay = false;
            //启动定时器
            TimerAnimationStart();
        }
        /// <summary>
        /// 当前页码赋值背景色
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="dr"></param>
        private void SetBtnColor(int pageIndex, string dr)
        {
            if (dr == "right")
            {
                if (pageIndex == 0)
                {
                    indexBtn.Children[0].SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C62F2F")));
                    indexBtn.Children[indexBtn.Children.Count - 1].SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C8C8C8")));
                    return;
                }
                indexBtn.Children[pageIndex].SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C62F2F")));
                indexBtn.Children[pageIndex - 1].SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C8C8C8")));
            }
            if (dr == "left")
            {
                if (pageIndex == indexBtn.Children.Count - 1)
                {
                    indexBtn.Children[indexBtn.Children.Count - 1].SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C62F2F")));
                    indexBtn.Children[0].SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C8C8C8")));
                    return;
                }
                indexBtn.Children[pageIndex].SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C62F2F")));
                indexBtn.Children[pageIndex + 1].SetValue(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C8C8C8")));
            }
        }
        /// <summary>
        /// 根据选中的页码获取对应页码前中后三张banner
        /// </summary>
        /// <param name="i"></param>
        public void GetLoctionBannerUrl(int i)
        {
            //启动动画时停止定时器
            timeranimation.Stop();
            //设置动画播放状态为真
            isplay = true;
            pageIndex = i;
            if (i == 0)
            {
                leftImg.Source = new BitmapImage(new Uri(bn[bn.Count - 1].imageUrl));
                centerImg.Source = new BitmapImage(new Uri(bn[0].imageUrl));
                rightImg.Source = new BitmapImage(new Uri(bn[1].imageUrl));
                leftTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[bn.Count - 1].titleColor));
                leftTypeTitle.Text = bn[bn.Count - 1].typeTitle;
                centerTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[0].titleColor));
                centerTypeTitle.Text = bn[0].typeTitle;
                rightTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[1].titleColor));
                rightTypeTitle.Text = bn[1].typeTitle;              
                return;
            }
            if (i == bn.Count - 1)
            {
                leftImg.Source = new BitmapImage(new Uri(bn[i - 2].imageUrl));
                centerImg.Source = new BitmapImage(new Uri(bn[bn.Count - 1].imageUrl));
                rightImg.Source = new BitmapImage(new Uri(bn[1].imageUrl));

                leftTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[i - 2].titleColor));
                leftTypeTitle.Text = bn[i - 2].typeTitle;
                centerTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[bn.Count - 1].titleColor));
                centerTypeTitle.Text = bn[bn.Count - 1].typeTitle;
                rightTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[1].titleColor));
                rightTypeTitle.Text = bn[1].typeTitle;
                return;
            }
            leftImg.Source = new BitmapImage(new Uri(bn[i - 1].imageUrl));
            centerImg.Source = new BitmapImage(new Uri(bn[i].imageUrl));
            rightImg.Source = new BitmapImage(new Uri(bn[i + 1].imageUrl));
            leftTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[i - 1].titleColor));
            leftTypeTitle.Text = bn[i - 1].typeTitle;
            centerTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[i].titleColor));
            centerTypeTitle.Text = bn[i].typeTitle;
            rightTitleColor.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[i - 1].titleColor));
            rightTypeTitle.Text = bn[i - 1].typeTitle;
        }
        #endregion

        /*
         * 即中间的border移动至：右
         * 右边的border移动至：左
         * 左边的border移动至：中
         */

        #region 左切换动画
        public void LeftAnimation()
        {
            //启动动画时停止定时器
            timeranimation.Stop();
            //设置动画播放状态为真
            isplay = true;
            //启动相应的动画

            //左向右滑动
            LefttoCenterAnimation();
            //中间向右滑动
            CentertoRightAnimation();
            //右向左滑动
            RighttoLeftAnimation();
        }
        //【仅注释此方法，以下代码均大多重复故不再注释】

        #region 左切换动画-左向中动画
        public void LefttoCenterAnimation()
        {
            b_left = Banners[Location.Left];
            string name = b_left.Name;
            Grid.SetZIndex(Banners[Location.Left], 3);
            GetOpacityGrid(b_left).Opacity = 0;
            Image image = (Image)FindName(name + "Img");
            image.Source = new BitmapImage(new Uri(bn[pageIndex].imageUrl));
            Border bd = (Border)FindName(name + "TitleColor");
            TextBlock tb = (TextBlock)bd.FindName(name + "TypeTitle");
            bd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[pageIndex].titleColor));
            tb.Text = bn[pageIndex].typeTitle;
            this.b_left.MouseLeftButtonUp += Bd_MouseLeftButtonDown;
            //bt = (Button)FindName("bt" + index.ToString());
            //bt.Background = Brushes.Red;
            ScaleTransform scale = new ScaleTransform();   //缩放  
            //scale.CenterX = 0;
            scale.CenterY = this.ActualHeight;
            TranslateTransform ts = new TranslateTransform();//平移
            TransformGroup group = new TransformGroup();
            group.Children.Add(scale);
            group.Children.Add(ts);
            Banners[Location.Left].RenderTransform = group;
            DoubleAnimation scaleAnimation = new DoubleAnimation()
            {
                From = 0.95,
                To = 1,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)
            };
            DoubleAnimation moveAnimation = new DoubleAnimation()
            {
                From = leftlocation,
                To = centerlocation,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)
            };
            scaleAnimation.Completed += new EventHandler(LeftAnimation_Completed);
            //  AnimationClock clock = scaleAnimation.CreateClock();  
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);

            //启动平移动画
            ts.BeginAnimation(TranslateTransform.XProperty, moveAnimation);
        }

        #endregion

        #region 左切换动画-中向右动画
        public void CentertoRightAnimation()
        {
            //记录动画结束后的位置，即当动画结束后中间的BORDER移动到右变成了右，代码：Banners[Location.Right] = b_center;
            b_center = Banners[Location.Center];
            //设置一下border的显示层级
            Grid.SetZIndex(Banners[Location.Center], 2);

            //获取透明遮盖图层，设置透明度
            /*
             * <Grid Background="Black" Panel.ZIndex="2"></Grid>
             * 透明遮盖图层在设计代码中的每个border内
             * 
             */
            GetOpacityGrid(b_center).Opacity = bopacity;
            //找到当前的border的名字然后赋值url
            string name = b_center.Name;
            Image image = (Image)FindName(name + "Img");

            Border bd = (Border)FindName(name + "TitleColor");
            TextBlock tb = (TextBlock)bd.FindName(name + "TypeTitle");

            //如果当前的地址index不必整个banner的数量多，以及index不小于0则左边永远是index+1
            if (pageIndex < bn.Count - 1 && pageIndex >= 0)
            {
                image.Source = new BitmapImage(new Uri(bn[pageIndex + 1].imageUrl));
                bd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[pageIndex + 1].titleColor));
                tb.Text = bn[pageIndex + 1].typeTitle;
            }
            else
            {
                //此时index为0，则回到最初的排列，点击滑动第一个变为index+1
                image.Source = new BitmapImage(new Uri(bn[0].imageUrl));
                bd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[0].titleColor));
                tb.Text = bn[0].typeTitle;
            }

            //定义一个缩放转换对象（用于banner从大到小的动画）
            ScaleTransform scale = new ScaleTransform();
            //需要设置中心点y坐标为控件的高度，不设置的话border是靠在顶部执行动画的。
            scale.CenterY = this.ActualHeight;

            //定义一个水平移动转换对象
            TranslateTransform ts = new TranslateTransform();

            //定义一个转换集合
            TransformGroup group = new TransformGroup();
            //将上面的缩放、平移转换对象添加到集合
            group.Children.Add(scale);
            group.Children.Add(ts);

            //将转换集合赋予给中心banner
            Banners[Location.Center].RenderTransform = group;


            //定义一个缩放动画
            DoubleAnimation scaleAnimation = new DoubleAnimation()
            {
                //从1（100%即默认比例）
                From = 1,
                //到0.95（95%即从默认比例缩小到95%的比例大小）
                To = 0.95,
                //设置缓动函数
                EasingFunction = easeFunction,
                //动画执行所需时间
                Duration = TimeSpan.FromSeconds(AnimationTime)


            };

            //定义一个移动动画（用于banner从左到右.....移动动画等）
            DoubleAnimation moveAnimation = new DoubleAnimation()
            {
                //从中心banner位置
                From = centerlocation,
                //移动到右banner位置
                To = rightlocation,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)

            };
            //启动缩放动画
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);
            //启动平移动画
            ts.BeginAnimation(TranslateTransform.XProperty, moveAnimation);

        }

        private void Bd_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var url = bn[pageIndex].url;
            MessageBox.Show(url);
        }
        #endregion

        #region 左切换动画-右向左动画
        public void RighttoLeftAnimation()
        {
            b_right = Banners[Location.Right];
            string name = b_right.Name;
            Grid.SetZIndex(Banners[Location.Right], 1);
            GetOpacityGrid(b_right).Opacity = bopacity;
            Image image = (Image)FindName(name + "Img");
            Border bd = (Border)FindName(name + "TitleColor");
            TextBlock tb = (TextBlock)bd.FindName(name + "TypeTitle");

            if (pageIndex == 0)
            {
                image.Source = new BitmapImage(new Uri(bn[bn.Count - 1].imageUrl));
                bd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[bn.Count - 1].titleColor));
                tb.Text = bn[bn.Count - 1].typeTitle;
            }
            if (pageIndex > 0 && pageIndex <= bn.Count - 1)
            {
                image.Source = new BitmapImage(new Uri(bn[pageIndex - 1].imageUrl));
                bd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[pageIndex - 1].titleColor));
                tb.Text = bn[pageIndex - 1].typeTitle;
            }
            ScaleTransform scale = new ScaleTransform();   //缩放  
            scale.CenterY = this.ActualHeight;
            TranslateTransform ts = new TranslateTransform();//平移


            TransformGroup group = new TransformGroup();
            group.Children.Add(scale);
            group.Children.Add(ts);


            Banners[Location.Right].RenderTransform = group;


            DoubleAnimation scaleAnimation = new DoubleAnimation()
            {
                From = 0.85,
                To = 0.95,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)
            };

            DoubleAnimation moveAnimation = new DoubleAnimation()
            {

                From = rightlocation,
                To = leftlocation,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)
            };

            //scaleAnimation.Completed += new EventHandler(scaleAnimation_Completed);  
            //  AnimationClock clock = scaleAnimation.CreateClock();  
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);

            //启动平移动画
            ts.BeginAnimation(TranslateTransform.XProperty, moveAnimation);

        }

        #endregion

        #region 动画结束
        private void LeftAnimation_Completed(object sender, EventArgs e)
        {
            //动画结束后将banner集合的位置重新设置
            Banners[Location.Left] = b_right;
            Banners[Location.Center] = b_left;
            Banners[Location.Right] = b_center;
            //此时动画结束
            isplay = false;
            //启动定时器
            TimerAnimationStart();
        }
        #endregion
        #endregion

        #region 右切换动画
        public void RightAnimation()
        {
            timeranimation.Stop();
            isplay = true;
            LefttoRightAnimation();
            CentertoLeftAnimation();
            RighttoCenterAnimation();
        }

        #region 右切换动画-左向右动画
        public void LefttoRightAnimation()
        {
            b_left = Banners[Location.Left];
            Grid.SetZIndex(Banners[Location.Left], 1);
            GetOpacityGrid(b_left).Opacity = bopacity;
            string name = b_left.Name;
            Image image = (Image)FindName(name + "Img");
            Border bd = (Border)FindName(name + "TitleColor");
            TextBlock tb = (TextBlock)bd.FindName(name + "TypeTitle");

            if (pageIndex == bn.Count - 1)
            {
                image.Source = new BitmapImage(new Uri(bn[0].imageUrl));
                bd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[0].titleColor));
                tb.Text = bn[0].typeTitle;
            }
            else
            {
                image.Source = new BitmapImage(new Uri(bn[pageIndex + 1].imageUrl));
                bd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[pageIndex + 1].titleColor));
                tb.Text = bn[pageIndex + 1].typeTitle;
            }
            ScaleTransform scale = new ScaleTransform(); //缩放  
            scale.CenterY = this.ActualHeight;
            TranslateTransform ts = new TranslateTransform();//平移
            TransformGroup group = new TransformGroup();
            group.Children.Add(scale);
            group.Children.Add(ts);
            Banners[Location.Left].RenderTransform = group;
            DoubleAnimation scaleAnimation = new DoubleAnimation()
            {
                From = 0.85,
                To = 0.95,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)
            };
            DoubleAnimation moveAnimation = new DoubleAnimation()
            {
                From = leftlocation,
                To = rightlocation,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)
            };
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);

            //启动平移动画
            ts.BeginAnimation(TranslateTransform.XProperty, moveAnimation);

        }

        #endregion

        #region 右切换动画-中向左动画
        public void CentertoLeftAnimation()
        {
            b_center = Banners[Location.Center];

            Grid.SetZIndex(Banners[Location.Center], 2);
            GetOpacityGrid(b_center).Opacity = bopacity;
            string name = b_center.Name;
            Image image = (Image)FindName(name + "Img");
            Border bd = (Border)FindName(name + "TitleColor");
            TextBlock tb = (TextBlock)bd.FindName(name + "TypeTitle");
            if (pageIndex == 0)
            {
                image.Source = new BitmapImage(new Uri(bn[bn.Count - 1].imageUrl));
                bd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[bn.Count - 1].titleColor));
                tb.Text = bn[bn.Count - 1].typeTitle;
            }
            else
            {
                image.Source = new BitmapImage(new Uri(bn[pageIndex - 1].imageUrl));
                bd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[pageIndex - 1].titleColor));
                tb.Text = bn[pageIndex - 1].typeTitle;
            }
            ScaleTransform scale = new ScaleTransform();   //缩放  
            scale.CenterY = this.ActualHeight;
            TranslateTransform ts = new TranslateTransform();//平移
            TransformGroup group = new TransformGroup();
            group.Children.Add(scale);
            group.Children.Add(ts);
            Banners[Location.Center].RenderTransform = group;
            DoubleAnimation scaleAnimation = new DoubleAnimation()
            {
                From = 1,
                To = 0.95,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)
            };

            DoubleAnimation moveAnimation = new DoubleAnimation()
            {

                From = centerlocation,
                To = leftlocation,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)

            };

            //scaleAnimation.Completed += new EventHandler(scaleAnimation_Completed);  
            //  AnimationClock clock = scaleAnimation.CreateClock();  
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);

            //启动平移动画
            ts.BeginAnimation(TranslateTransform.XProperty, moveAnimation);
        }



        #endregion

        #region 右切换动画-右向中动画
        public void RighttoCenterAnimation()
        {
            b_right = Banners[Location.Right];
            //SetZindex(b_right);
            Grid.SetZIndex(Banners[Location.Right], 3);
            GetOpacityGrid(b_right).Opacity = 0;
            string name = b_right.Name;
            Image image = (Image)FindName(name + "Img");
            image.Source = new BitmapImage(new Uri(bn[pageIndex].imageUrl));
            Border bd = (Border)FindName(name + "TitleColor");
            TextBlock tb = (TextBlock)bd.FindName(name + "TypeTitle");
            bd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(bn[pageIndex].titleColor));
            tb.Text = bn[pageIndex].typeTitle;
            //bt = (Button)FindName("bt" + index.ToString());
            //bt.Background = Brushes.Red;
            ScaleTransform scale = new ScaleTransform();   //缩放  
            //scale.CenterX = 0;
            scale.CenterY = this.ActualHeight;
            TranslateTransform ts = new TranslateTransform();//平移
            TransformGroup group = new TransformGroup();
            group.Children.Add(scale);
            group.Children.Add(ts);
            Banners[Location.Right].RenderTransform = group;
            DoubleAnimation scaleAnimation = new DoubleAnimation()
            {
                To = 1,
                From = 0.95,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)
            };
            DoubleAnimation moveAnimation = new DoubleAnimation()
            {

                From = rightlocation,
                To = centerlocation,
                EasingFunction = easeFunction,
                Duration = TimeSpan.FromSeconds(AnimationTime)

            };
            scaleAnimation.Completed += new EventHandler(RightAnimation_Completed);
            //  AnimationClock clock = scaleAnimation.CreateClock();  
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);

            //启动平移动画
            ts.BeginAnimation(TranslateTransform.XProperty, moveAnimation);
        }

        #endregion

        #region 动画结束
        private void RightAnimation_Completed(object sender, EventArgs e)
        {
            Banners[Location.Left] = b_center;
            Banners[Location.Center] = b_right;
            Banners[Location.Right] = b_left;
            isplay = false;
            TimerAnimationStart();
        }
        #endregion
        #endregion

        #region 初始化设置控件位置
        //定义一个枚举类用于标识左中右三个banner(border)，方便操作时获取到。
        public enum Location
        {
            Left, Center, Right
        }
        //设置三个border的大小和位置
        public void SetLocation(Location l, Border g)
        {

            //banner的大小
            g.Width = 540;
            g.Height = 200;

            //给除中间banner外的border缩小一些
            ScaleTransform scaleTransform = new ScaleTransform();
            scaleTransform.ScaleX = 0.95;
            scaleTransform.ScaleY = 0.95;
            scaleTransform.CenterY = this.ActualHeight;
            //获取设置遮盖层的透明度
            Grid opacity_grid = GetOpacityGrid(g);
            opacity_grid.Opacity = bopacity;
            switch (l)
            {
                case Location.Left:

                    TranslateTransform tt_left = new TranslateTransform()
                    {
                        X = 0
                    };
                    TransformGroup group_left = new TransformGroup();
                    group_left.Children.Add(tt_left);
                    group_left.Children.Add(scaleTransform);
                    g.RenderTransform = group_left;
                    break;
                case Location.Center:
                    opacity_grid.Opacity = 0;

                    TransformGroup group_center = new TransformGroup();

                    //计算中心banner的x位置
                    centerlocation = (this.ActualWidth - g.ActualWidth) / 2;
                    TranslateTransform tt_center = new TranslateTransform()
                    {
                        X = centerlocation
                    };
                    group_center.Children.Add(tt_center);
                    g.RenderTransform = group_center;
                    Grid.SetZIndex(g, 3);
                    break;
                case Location.Right:
                    //Grid.SetZIndex(g, 3);

                    //计算右banner的X位置
                    rightlocation = (this.ActualWidth - Banners[Location.Left].ActualWidth * 0.95);

                    TranslateTransform tt_right = new TranslateTransform()
                    {
                        X = rightlocation
                    };
                    TransformGroup group_right = new TransformGroup();
                    //这里要注意先后顺序，否则位置会有偏差，必须先缩放再设置X坐标。
                    group_right.Children.Add(scaleTransform);
                    group_right.Children.Add(tt_right);
                    g.RenderTransform = group_right;


                    break;
            }

        }
        #endregion

        #region 获取透明覆盖层
        public Grid GetOpacityGrid(DependencyObject g)
        {
            Grid opacity_grid = GetChild<Grid>(g, typeof(Grid));
            opacity_grid = GetChild<Grid>(opacity_grid, typeof(Grid));
            return opacity_grid;
        }
        public T GetChild<T>(DependencyObject obj, Type typename) where T : FrameworkElement
        {
            DependencyObject child = null;
            List<T> childList = new List<T>();

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);

                if (child is T && (((T)child).GetType() == typename))
                {
                    return ((T)child);
                }

            }
            return null;
        }
        #endregion

        #region 定时唤醒动画
        public void TimerAnimationStart()
        {
            if (timeranimation.IsEnabled == false)
            {
                timeranimation.Start();
            }
            timeranimation.Tick += (e, c) =>
            {
                timeranimation.Stop();
                if (isplay == false)
                {
                    if (pageIndex < bn.Count - 1)
                    {
                        pageIndex++;
                    }
                    else
                    {
                        pageIndex = 0;
                    }
                    RightAnimation();
                    SetBtnColor(pageIndex, "right");
                }
            };
        }
        #endregion

        #endregion
    }
}
